package com.yunzo.coc.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * Makedate:2014年9月1日 下午4:59:22
 * 
 * @author Administrator
 * @version V1.0
 */
public class HttpClientUtil {

	private static final Logger logger = Logger.getLogger(HttpClientUtil.class);

	public static void main(String[] args) {
		// TODO Auto-generated method stub
//		String requestBody = "{\"name\":\"王五\",\"age\":60,\"createDate\":1408377600000,\"modifyDate\":1409068800000}";
//		try {
//			String result = HttpClientUtil.httpPost(
//					"http://localhost:8080/webmvc/demorest/save", requestBody,
//					"application/json", "UTF-8");
//			System.out.println("result======" + result);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		test();
	}

	//君诚科技短信平台测试
	public static  void test()
	{
		String content = "【网投网】您的验证码是：752255。"; 

		try {
			Map<String, String> params = new HashMap<String, String>();  
			params.put("username", "yzkj");  
			params.put("password",StringUtils.encodePassword("yzkj"+StringUtils.encodePassword("hredhy7w", "md5"), "md5"));  
			params.put("mobile", "13540148430");  
			params.put("content",content);  
			params.put("dstime", "");  

		   String t=post("http://www.jc-chn.cn/smsSend.do",params);
		  
		   System.out.println(t);
		} catch (Exception e) {
			e.printStackTrace();
		}   
	}
	public static String post(String url, Map<String, String> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		String body = null;

		System.out.println("create httppost:" + url);
		HttpPost post = postForm(url, params);

		body = invoke(httpclient, post);

		httpclient.getConnectionManager().shutdown();

		return body;
	}

	private static HttpPost postForm(String url, Map<String, String> params) {

		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}

		try {
			System.out.println("set utf-8 form entity to httppost");
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return httpost;
	}

	private static String invoke(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {

		HttpResponse response = sendRequest(httpclient, httpost);
		String body = paseResponse(response);

		return body;
	}

	private static String paseResponse(HttpResponse response) {
		System.out.println("get response from http server..");
		HttpEntity entity = response.getEntity();

		System.out.println("response status: " + response.getStatusLine());
		String charset = EntityUtils.getContentCharSet(entity);
		System.out.println(charset);

		String body = null;
		try {
			body = EntityUtils.toString(entity);
			System.out.println(body);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return body;
	}

	private static HttpResponse sendRequest(DefaultHttpClient httpclient,
			HttpUriRequest httpost) {
		System.out.println("execute post...");
		HttpResponse response = null;

		try {
			response = httpclient.execute(httpost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	public static String httpPost(String url, String data, String contentType,
			String encode) throws Exception {
		long startTime = System.currentTimeMillis();
		InputStream instream = null;
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");
		HttpClient httpClient = new HttpClient();
		PostMethod httpPost = new PostMethod(url);
		try {

			httpPost.setRequestHeader("Content-Type", contentType);

			RequestEntity requestEntity = new StringRequestEntity(data,
					contentType, encode);
			httpPost.setRequestEntity(requestEntity);
			httpClient.executeMethod(httpPost);

			if (httpPost.getStatusCode() == HttpStatus.SC_OK) {

				Header headers[] = httpPost.getResponseHeaders();
				for (Header header : headers) {
					logger.info(header.getName() + "||" + header.getValue());
				}
				instream = httpPost.getResponseBodyAsStream();
				if (instream == null) {
					logger.error("Result is NULL. URL:" + url);
				}

				in = new BufferedReader(
						new InputStreamReader(instream, "UTF-8"));

				String line = null;
				while ((line = in.readLine()) != null) {
					sb.append(line);
					sb.append("\n");
				}

			}
		} catch (Exception e) {
			if (logger.isInfoEnabled()) {
				logger.info("HttpClientUtil-Exception: ", e);
			}
			throw e;
		} finally {
			if (in != null) {
				in.close();
			}

			httpPost.releaseConnection();
		}
		logger.info("the result from HttpClientUtil:result="
				+ (null != sb.toString() ? sb.toString().trim() : null));
		long endTime = System.currentTimeMillis();
		logger.info("结束调用：HttpClientUtil的httpPostWithJSON方法" + " ["
				+ Long.toString(endTime - startTime) + "]");

		return sb.toString();
	}

}
